<?php
session_start();

// 检查是否已安装
$install_file = '../data/installed.txt';
if (!file_exists($install_file)) {
    header('Location: ../install/');
    exit;
}

// 检查管理员登录状态
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header('Location: login.php');
    exit;
}

// 加载配置
if (!file_exists('../data/config.php')) {
    die('配置文件不存在');
}
require_once '../data/config.php';

// 数据库连接
try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}

// 获取统计信息
$stmt = $pdo->query("SELECT COUNT(*) as user_count FROM users");
$user_count = $stmt->fetch(PDO::FETCH_ASSOC)['user_count'];

$stmt = $pdo->query("SELECT COUNT(*) as message_count FROM chat_history");
$message_count = $stmt->fetch(PDO::FETCH_ASSOC)['message_count'];

// 获取最近的聊天记录
$stmt = $pdo->query("SELECT user_ip, message, response, timestamp FROM chat_history ORDER BY timestamp DESC LIMIT 10");
$recent_chats = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 获取用户列表
$stmt = $pdo->query("SELECT ip_address, created_at FROM users ORDER BY created_at DESC");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>lanxAI 管理后台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fa;
            color: #333;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            font-size: 1.5em;
            font-weight: 600;
        }
        
        .logout {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
        }
        
        .logout:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 20px;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            text-align: center;
        }
        
        .stat-card h3 {
            font-size: 1.1em;
            color: #666;
            margin-bottom: 10px;
        }
        
        .stat-card .number {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
        }
        
        .content-section {
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            margin-bottom: 30px;
            overflow: hidden;
        }
        
        .section-header {
            padding: 15px 20px;
            background: #f8f9fa;
            border-bottom: 1px solid #eee;
            font-weight: 600;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        th {
            background: #f8f9fa;
            font-weight: 600;
        }
        
        tr:hover {
            background: #f8f9fa;
        }
        
        .footer {
            text-align: center;
            padding: 20px;
            color: #666;
            font-size: 14px;
        }
        
        .actions {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 0.9em;
        }
        
        .view-btn {
            background: #28a745;
            color: white;
        }
        
        .delete-btn {
            background: #dc3545;
            color: white;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>lanxAI 管理后台</h1>
        <form method="post" style="display: inline;">
            <input type="hidden" name="logout" value="1">
            <button type="submit" class="logout">退出登录</button>
        </form>
    </div>
    
    <div class="container">
        <div class="stats">
            <div class="stat-card">
                <h3>总用户数</h3>
                <div class="number"><?php echo $user_count; ?></div>
            </div>
            <div class="stat-card">
                <h3>总消息数</h3>
                <div class="number"><?php echo $message_count; ?></div>
            </div>
            <div class="stat-card">
                <h3>当前模型</h3>
                <div class="number"><?php echo htmlspecialchars($default_model); ?></div>
            </div>
        </div>
        
        <div class="content-section">
            <div class="section-header">最近聊天记录</div>
            <table>
                <thead>
                    <tr>
                        <th>IP地址</th>
                        <th>用户消息</th>
                        <th>AI回复</th>
                        <th>时间</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recent_chats as $chat): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($chat['user_ip']); ?></td>
                        <td><?php echo htmlspecialchars(substr($chat['message'], 0, 50)) . (strlen($chat['message']) > 50 ? '...' : ''); ?></td>
                        <td><?php echo htmlspecialchars(substr($chat['response'], 0, 50)) . (strlen($chat['response']) > 50 ? '...' : ''); ?></td>
                        <td><?php echo htmlspecialchars($chat['timestamp']); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($recent_chats)): ?>
                    <tr>
                        <td colspan="4" style="text-align: center;">暂无聊天记录</td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <div class="content-section">
            <div class="section-header">用户列表</div>
            <table>
                <thead>
                    <tr>
                        <th>IP地址</th>
                        <th>注册时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($user['ip_address']); ?></td>
                        <td><?php echo htmlspecialchars($user['created_at']); ?></td>
                        <td class="actions">
                            <button class="btn view-btn" onclick="viewUser('<?php echo htmlspecialchars($user['ip_address']); ?>')">查看</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($users)): ?>
                    <tr>
                        <td colspan="3" style="text-align: center;">暂无用户</td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <div class="footer">
        <p>LANX开源AI</p>
    </div>

    <script>
        function viewUser(ip) {
            window.location.href = 'user_chat.php?ip=' + encodeURIComponent(ip);
        }
        
        // 处理登出
        <?php 
        if (isset($_POST['logout']) && $_POST['logout'] == '1') {
            $_SESSION['admin_logged_in'] = false;
            unset($_SESSION['admin_logged_in']);
            header('Location: login.php');
            exit;
        }
        ?>
    </script>
</body>
</html>